/**
 * auth: zhukaijun
 * date: 2021-12-11
 * des: data storage with expire time
 */
export default {
    expireKey(name) {
        return name + "_expire";
    },
    del(name) {
        localStorage.removeItem(name);
    },
    has(name) {
        return this.getIfExits(name);
    },
    save(name, value, expire) {
        if (expire) {
            localStorage.setItem(this.expireKey(name), Date.now() + Math.abs(expire * 1000));
        }
        localStorage.setItem(name, value)
        return value;
    },
    getIfExits(name, dataGetter, expire) {
        dataGetter = dataGetter || (() => undefined);
        let expired = localStorage.getItem(this.expireKey(name));
        if (expired) {
            if (expired < Date.now()) {
                let sData = dataGetter(name);
                if (!sData) {
                    localStorage.removeItem(this.expireKey(name));
                    this.del(name);
                    return undefined;
                }
                if (!expire) {
                    throw new Error('expire time must not eq zero');
                }
                return this.save(name, sData, expire);
            }
        }
        let data = localStorage.getItem(name);
        if (data) {
            return data;
        }
        let sData = dataGetter(name);
        if (!sData) {
            return 0;
        }
        return this.save(name, sData, expire);
    },
    get(name) {
        return localStorage.getItem(name);
    },
    expired(name) {
        localStorage.removeItem(this.expireKey(name));
        this.del(name);
    }
}